﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Walson.Time.Tracker
{
    /// <summary>
    /// 高精度时间跟踪
    /// </summary>
    public class TrackTime
    {
        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpm_Frequency);

        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        private long m_StartTime, m_StopTime, m_Freq;

        /// <summary>
        /// 高精度时间测量
        /// </summary>
        public TrackTime()
        {
            this.m_StartTime=0;
            this.m_StopTime=0;
            if(QueryPerformanceFrequency(out m_Freq)==false)
            {
                throw new Exception();
            }
        }

        /// <summary>
        /// 启动时间测量
        /// </summary>
        public void Start()
        {
            System.Threading.Thread.Sleep(0);
            QueryPerformanceCounter(out m_StartTime);
        }

        /// <summary>
        /// 距开始计时到计时结束所经过的时长（毫秒）
        /// </summary>
        public double DurationMS
        {
            get
            {
                QueryPerformanceCounter(out m_StopTime);
                return (double)(m_StopTime - m_StartTime) * 1000.0 / (double)m_Freq;
            }
        }
    }
}
